// https://css-tricks.com/prevent-page-scrolling-when-a-modal-is-open/
function disable_body_scroll() {
  const scroll_y = window.scrollY;

  document.body.classList.add('fixed');
  document.body.classList.add('h-screen');
  document.body.classList.add('overflow-y-hidden');

  document.body.style.top = `-${scroll_y}px`;
}

function enable_body_scroll() {
  const scroll_y = document.body.style.top;

  document.body.classList.remove('fixed');
  document.body.classList.remove('h-screen');
  document.body.classList.remove('overflow-y-hidden');

  document.body.style.top = '';
  window.scrollTo(0, parseInt(scroll_y || '0') * -1);
}

function get_ios_version() {
  if (/iP(hone|od|ad)/.test(navigator.platform)) {
    // iOS device
    const ua = navigator.userAgent;
    const match = ua.match(/OS (\d+)_(\d+)_?(\d+)?/);
    if (match) {
      return [
        parseInt(`${match[1]}`, 10),
        parseInt(`${match[2]}`, 10),
        parseInt(`${match[3] || 0}`, 10),
      ];
    }
  }
  return null;
}

function get_safari_version() {
  const ua = navigator.userAgent;
  const match = ua.match(/Version\/([\d.]+)/);
  if (match && match[1]) {
    return parseFloat(match[1]);
  }
  return null;
}

function isChildOf(parent: HTMLElement, child: HTMLElement, maxDepth = 20): boolean {
  let depth = 1;
  let parentNode = child.parentNode;
  while (parentNode && depth <= maxDepth) {
    if (parentNode === parent) {
      return true;
    }
    ++depth;
    parentNode = parentNode.parentNode;
  }
  return false;
}

export { disable_body_scroll, enable_body_scroll, get_ios_version, get_safari_version, isChildOf };
